import { Component, Input, Injector, ViewChild } from '@angular/core';
import { NzDrawerRef } from 'ng-zorro-antd';
import { FormBuilder } from '@angular/forms';
import { AppComponentBase } from '@abp/components';
import * as _ from 'lodash';
import {
  UserServiceProxy,
  UpdateUserPermissionsInput,
  EntityDtoOfInt64,
} from '@abp/service-proxies/service-proxies';
import { PermissionTreeComponent } from '../../components/permission-tree/permission-tree.component';

@Component({
  selector: 'edit-users-permissionsDrawer',
  templateUrl: './edit-user-permissions.component.html',
  styleUrls: ['./edit-user-permissions.component.less'],
})
export class EditUserPermissionsComponent extends AppComponentBase {
  @Input() id?: number;
  @ViewChild('permissionTree')
  permissionTree: PermissionTreeComponent;

  isLoadingBtn = false;

  constructor(
    injector: Injector,
    private drawerRef: NzDrawerRef,
    private fb: FormBuilder,
    private userService: UserServiceProxy,
  ) {
    super(injector);
  }

  ngOnInit() {
    this.userService
      .getUserPermissionsForEdit(this.id)
      .subscribe(userPermissionsResult => {
        this.permissionTree.editData = userPermissionsResult;
      });
  }

  submitForm(): void {
    let input = new UpdateUserPermissionsInput();
    input.id = this.id;
    input.grantedPermissionNames = this.permissionTree.getGrantedPermissionNames();

    this.isLoadingBtn = true;
    this.userService.updateUserPermissions(input).subscribe(() => {
      this.isLoadingBtn = false;
      this.notify.success('操作成功！');
      this.drawerRef.close(true);
    });
  }

  resetPermissions() {
    let input = new EntityDtoOfInt64();
    input.id = this.id;

    this.userService.resetUserSpecificPermissions(input).subscribe(() => {
      this.notify.success('重置成功');
      this.userService.getUserPermissionsForEdit(this.id).subscribe(result => {
        this.permissionTree.editData = result;
      });
    });
  }

  close(): void {
    this.drawerRef.close(false);
  }
}
